const request = require('superagent');
const fs = require('fs');

const email = ''; //极简图传的用户名
const password = '';  //密码
const loginUrl = 'http://jiantuku.com/api/user/signin';
const photoUrl = process.argv[2] === undefined ? '' : process.argv[2]; //图片URL
if (!photoUrl) {
    return 'invalid photoUrl';
}
(async () => {
    const loginRes = await request
        .post(loginUrl)
        .send({ email, password })
    const { accessToken, user: { id, albumId, metas } } = loginRes.body;
    const cookie = loginRes.header['set-cookie'];
    for (let [key, value] of Object.entries(metas)) {
        cookie.push(`${key}=${value}`);
    }
    const rawcookie = cookie.join('; ');

    const photo = await request.get(photoUrl);
    const data = photo.body.toString('base64');

    try{
        const uploadRes = await request
        .post(`http://jiantuku.com/api/users/${id}/action/upload`)
        .query({ name: 'test.jpg' })
        .query({ type: 'image/jpeg' })
        .query({ albumId })
        .query({ storage: 'custom' })
        .set({ Cookie: rawcookie, authorization: `Bearer ${accessToken}`, 'Content-Type': 'text/plain' })
        .send(data);
        return uploadRes.body.url;
    }catch(e){
        return 'invalid photo url';
    }
})();

